#include <iostream>
#include <string>
#include <unordered_map>
#include <cstring>
#include <sys/types.h>
#include <arpa/inet.h>
#include <strings.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
#include "Log.hpp"

using std::cout;
using std::endl;
void *Listen(void *arg)
{
    while(1)
    {
        int *socketfd = (int *)arg;
    struct sockaddr_in server1;
    socklen_t len;
    char buffer[1024];
    ssize_t n = recvfrom(*socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server1, &len);
    if (n > 0)
    {
        buffer[n] = 0;
        cout << buffer << endl;
    }
    }
    return nullptr;
}

int main()
{
    int socketfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (socketfd < 0)
    {
        cout << "socket error" << endl;
        exit(1);
    }
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_addr.s_addr = inet_addr("116.204.73.161");
    server.sin_family = AF_INET;
    server.sin_port = htons(8888);

    int num = 0;

    while (true)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Listen, &socketfd);
        if (num == 0)
        {
            cout << "Please Enter Your Name:" << endl;
            std::string name;
            std::getline(std::cin, name);
            std::string message = "name:" + name;
            sendto(socketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
            num++;
        }
        else
        {
            cout << "Please Enter What You Want To Say# " << endl;
            std::string message;
            std::getline(std::cin, message);
            sendto(socketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
            num++;
        }
    }

    return 0;
}